/**
 * Copyright (C) 2025 pony working team
 * SPDX-License-Identifier: MulanPSL-2.0
 */

/* includes (local) ----------------------------------------------------------*/
#include <bsp_key.h>
/* includes (standard library, system) ---------------------------------------*/
/* includes (other library) --------------------------------------------------*/
/* includes (project) --------------------------------------------------------*/
#include <hal_gpio.h>
#include <x_module.h>

/* defines -------------------------------------------------------------------*/
/* typedefs ------------------------------------------------------------------*/

typedef struct key_dev {
    hal_key_t key;
    hal_gpio_t gpio;
} key_dev_t;

typedef struct key_cfg {
    uint8_t id;
    uint8_t gpio;
    uint8_t pin;
} key_cfg_t;

/* macro ---------------------------------------------------------------------*/
/* variables (extern) --------------------------------------------------------*/
/* variables (local) ---------------------------------------------------------*/

static key_dev_t key_devs[BSP_KEY_ID_NUM];

/* variables (global) --------------------------------------------------------*/
/* inlines -------------------------------------------------------------------*/
/* functions -----------------------------------------------------------------*/

static uint8_t __key_get_state(uint8_t id)
{
    uint8_t v = 0;
    hal_gpio_t *gpio = &(key_devs[id].gpio);

    hal_gpio_read(gpio, &v);

    return (v == 1) ? HAL_KEY_STATE_PRESSED : HAL_KEY_STATE_RELEASED;
}

static int __key_init(uint8_t id, uint8_t gpio, uint8_t pin)
{
    key_dev_t *dev = &key_devs[id];

    dev->gpio.gpio = gpio;
    dev->gpio.pin = pin;
    dev->gpio.mode = HAL_GPIO_MODE_INPUT;
    dev->gpio.pull = HAL_GPIO_NOPULL;
    dev->gpio.speed = HAL_GPIO_SPEED_FREQ_HIGH;
    if (hal_gpio_init(&dev->gpio) != 0) {
        return -1;
    }

    dev->key.id = id;
    dev->key.get_state = __key_get_state;
    hal_key_attach(&dev->key);

    return 0;
}

static int bsp_key_init(void)
{
    int ret;

    key_cfg_t key_cfg[] = {
        {BSP_KEY_ID_1, SYM_C2N(C), 13},
    };

    for (size_t i = 0; i < ARRAY_SIZE(key_cfg); i++) {
        key_cfg_t *cfg = &key_cfg[i];
        if ((ret = __key_init(cfg->id, cfg->gpio, cfg->pin)) != 0) {
            return ret;
        }
    }

    return 0;
}

MODULE_INIT(board, bsp_key_init);
